package com.duapk.search.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.duapk.common.SearchResult;
import com.duapk.search.bean.SearchRequest;
import com.duapk.search.constant.Constant;
import com.duapk.search.util.JSONUtils;
import com.duapk.search.util.StringTools;
import com.duapk.search.work.SearchProxy;

/**
 * 搜索接口
 * 
 * @Package: com.duapk.search.servlet
 * @ClassName: SearchServlet
 * @author: jiangzheng
 * @date: Apr 4, 2011 7:42:45 PM
 * 
 */
@SuppressWarnings("serial")
public class SearchServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding(Constant.UTF_ENCODING);
		resp.setContentType("tex/html;charset=" + Constant.UTF_ENCODING);
		PrintWriter out = resp.getWriter();

		SearchRequest request = createSearchRequest(req);
		SearchResult searchResult = SearchProxy.search(request);
		out.write(JSONUtils.toJson(searchResult));
		out.flush();
		out.close();
	}

	/**
	 * 创建搜索请求对象
	 * 
	 * @Title: createSearchRequest
	 * @author: jiangzheng
	 * @date: Apr 4, 2011 10:36:28 PM
	 * @param req
	 * @return
	 */
	private SearchRequest createSearchRequest(HttpServletRequest req) {
		SearchRequest request = new SearchRequest();
		request.setKeyword(req.getParameter("q"));
		request.setPageSize(StringTools.parseInt(req.getParameter("s"), 10));
		request.setPid(StringTools.parseInt(req.getParameter("p"), 1));
		request.setVersion(StringTools.parseFloat(req.getParameter("v"), 0));
		request.setField(req.getParameter("f"));
		request.setStar(StringTools.parseFloat(req.getParameter("star"), -1f));
		request.setPubtime(StringTools
				.parseLong(req.getParameter("pubtime"), 0));
		request.setSize(StringTools.parseInt(req.getParameter("size"), 0));
		request.setCategory(req.getParameter("t"));
		return request;
	}
}
